import requests
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.date import DateTrigger
from fastapi import APIRouter, Depends, HTTPException, status, Query, WebSocket, WebSocketDisconnect
from sqlalchemy.orm import Session
from typing import Any, Optional, List, Dict
from app import crud, models, schemas
from app.api import deps
from app.models import BroadcastTask, BroadcastLog
from pydantic.types import UUID4
from datetime import datetime, timedelta
router = APIRouter()


@router.get("/search_logs", summary="检索播报日志")
def search_tasks(
        search: Optional[str] = None,
        start_date: Optional[datetime] = None,
        end_date: Optional[datetime] = None,
        target_department: Optional[str] = None,
        trigger_type: Optional[str] = None,
        db: Session = Depends(deps.get_db),
        # with_archived: Optional[bool] = False,
        page_size: int = Query(10, alias="page_size"),  # 每页显示多少条数据
        current_page: int = Query(1, alias="current_page")  # 当前页码
) -> Any:
    """
    通过关键字/日期/部门/触发类型检索 broadcast_tasks。
    """
    with_archived = False
    # 构建查询对象
    query = db.query(BroadcastLog)
    if search:
        query = query.filter(
            (BroadcastLog.target_name.ilike(f"%{search}%")) |
            (BroadcastLog.broadcast_task_name.ilike(f"%{search}%"))
        )
    if start_date:
        query = query.filter(BroadcastLog.created_at >= start_date)
    if end_date:
        query = query.filter(BroadcastLog.created_at <= end_date)
    if target_department:
        query = query.filter(BroadcastLog.target_department == target_department)
    if trigger_type:
        query = query.filter(BroadcastLog.trigger_type == trigger_type)
    query = crud.broadcast_log.filter_archivable(query, with_archived)
    # 计算总记录数
    total = query.count()
    # 分页查询
    broadcast_logs = query.offset((current_page - 1) * page_size).limit(page_size).all()
    result = []
    for broadcast_log in broadcast_logs:
        broadcast_time = broadcast_log.broadcast_time
        broadcast_time_str = broadcast_time.strftime("%Y年%m月%d日 %H:%M:%S")
        result.append({
            "id": broadcast_log.id,
            "target_name": broadcast_log.target_name,
            "target_department": broadcast_log.target_department,
            "broadcast_task_name": broadcast_log.broadcast_task_name,
            "broadcast_time": broadcast_time_str,
            "trigger_type": broadcast_log.trigger_type,
        })

    return {"total": total, "items": result}


@router.get("/departments", response_model=List[str], summary="获取部门列表")
def get_departments(
        db: Session = Depends(deps.get_db)
) -> Any:
    """
    获取所有播报对象的所属部门列表.
    """
    # 从播报对象表中检索所有的播报对象
    broadcast_targets = crud.broadcast_target.get_all(db=db)

    # 使用集合来存储唯一的部门名称
    departments = set()

    for target in broadcast_targets:
        departments.add(target.department)

    # 将集合转换为列表
    department_list = list(departments)

    return department_list
